package com.peas.platform.framework.mybatisplus.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.peas.platform.common.core.constant.Constants;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

public class PageUtil {

    public static <E> Page<Map<String, Object>> copyPage(Page<E> page) {
        Page<Map<String, Object>> r = Page.of(page.getCurrent(), page.getSize(), page.getTotal(), page.searchCount());
        r.setOrders(page.orders());
        r.setPages(page.getPages());
        if (CollUtil.isNotEmpty(page.getRecords())) {
            List<Map<String, Object>> list = new ArrayList<>();
            page.getRecords().forEach(e -> list.add(BeanUtil.beanToMap(e)));
            r.setRecords(list);
        }
        return r;
    }

    public static <T, E> Page<T> copyPage(Page<E> page, Class<T> clazz) {
        Page<T> r = Page.of(page.getCurrent(), page.getSize(), page.getTotal(), page.searchCount());
        r.setOrders(page.orders());
        r.setPages(page.getPages());
        r.setRecords(BeanUtil.copyToList(page.getRecords(), clazz));
        return r;
    }

    public static <T> Page<T> genPager(Integer pageNum, Integer pageSize, String sortField, String sortType) {
        sortField = StrUtil.isBlank(sortField) ? Constants.DEFAULT_SORT_FIELD : sortField;
        OrderItem order = StrUtil.equalsIgnoreCase(Constants.SORT_ASC, sortType) ? OrderItem.asc(sortField) : OrderItem.desc(sortField);
        Page<T> pager = new Page<>();
        pager.setCurrent(pageNum == null ? Constants.DEFAULT_PAGE_NUM : pageNum);
        pager.setSize(pageSize == null ? Constants.DEFAULT_PAGE_SIZE : pageSize);
        pager.setOrders(Collections.singletonList(order));
        return pager;
    }

}
